local desc_1v2 = [[
  # 欢乐斗地主模式简介

  ___

  总体规则类似身份局。游戏由三人进行，一人扮演地主（主公），其他两人扮演农民（反贼）。

  地主选将框+2，增加一点体力上限和体力，且拥有以下额外技能：

  - **飞扬**：判定阶段开始时，你可以弃置两张手牌并弃置自己判定区内的一张牌。

  - **跋扈**：锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张杀。

  当农民被击杀后，另一名农民可以选择：摸两张牌，或者回复一点体力。

  *击杀农民的人没有摸三张牌的奖励。*

  胜利规则与身份局一致。
]]

-- Because packages are loaded before gamelogic.lua loaded
-- so we can not directly create subclass of gamelogic in the top of lua

local U = require "packages/utility/utility"

local han_generals = { "hiddenone" , "hiddenone" , "hiddenone"}



local QDZ_1v2_getLogic = function()
  local QDZ_1v2_logic = GameLogic:subclass("QDZ_1v2_logic")

  function QDZ_1v2_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {nil, nil, {"lord", "rebel", "rebel"}}
  end

  function QDZ_1v2_logic:chooseGenerals()
    local room = self.room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    local lord = room:getLord()
    room:setCurrent(lord)
    -- 询问选将
    local others = room:getNGenerals( 2* generalNum )
    local to_ask = table.filter(room.players, function(p) return p.role ~= "rebel" end)
    local req = Request:new(to_ask, "AskForGeneral")
    req.focus_text = "AskForGeneral"
    for i, p in ipairs(room.players) do
      local avatar = han_generals[i]
      room:setPlayerGeneral(p, avatar, true)
      room:broadcastProperty(p, "general")
    end
  end


  function QDZ_1v2_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
  
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill.lordSkill then
        return
      end
      if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
        return
      end
  
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
    end
  end

  return QDZ_1v2_logic
end

local m_feiyang = fk.CreateTriggerSkill{
  name = "m_feiyang",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player.phase == Player.Judge and
      #player:getCardIds(Player.Hand) >= 2 and
      #player:getCardIds(Player.Judge) > 0
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 2, 2, false, self.name, true, ".", "#m_feiyang-invoke", true)
    if #cards == 2 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    local jcards = player:getCardIds("j")
    if #jcards == 0 then return end
    local card = #jcards == 1 and jcards[1] or room:askForCardChosen(player, player, "j", self.name)
    room:throwCard({card}, self.name, player, player)
  end
}
Fk:addSkill(m_feiyang)
local m_bahubuff = fk.CreateTargetModSkill{
  name = "#m_bahubuff",
  residue_func = function(self, player, skill, scope)
    if player:hasSkill(self) and skill.trueName == "slash_skill"
      and scope == Player.HistoryPhase then
      return 1
    end
  end,
}
local m_bahu = fk.CreateTriggerSkill{
  name = "m_bahu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
m_bahu:addRelatedSkill(m_bahubuff)
Fk:addSkill(m_bahu)



local QDZ_1v2_rule = fk.CreateTriggerSkill{
  name = "#QDZ_1v2_rule",
  priority = 0.001,
  mute = true,
  events = {fk.BuryVictim,fk.GamePrepared},
  can_trigger = function(self, event, target, player, data)
    if event == fk.BuryVictim then
      return target ~= player and target.rest == 0 and target.role == "rebel" and player.role == "rebel" and not player.dead
    end
    if event == fk.GamePrepared then
      local room = player.room
      local players = room.players
      local i = 0
      for _, p in ipairs(players) do
        if p:usedSkillTimes(self.name, Player.HistoryGame) == 0 then
          i = i + 1
        end
      end
      if i == #players then
        return true
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- 遗产
    if event == fk.BuryVictim then
      local choices = {"QDZ_1v2_draw2", "Cancel"}
      if player:isWounded() then
        table.insert(choices, 2, "QDZ_1v2_heal")
      end
      local choice = room:askForChoice(player, choices, self.name ,"#QDZ_1v2_rule")
      if choice == "QDZ_1v2_draw2" then
        player:drawCards(2, self.name)
      else
        room:recover{ who = player, num = 1, skillName = self.name }
      end
    -- 选将
    else
      local generalNum = room.settings.generalNum
      local players = room.players
      Fk:currentRoom().settings.gameMode = "m_1v2_mode" -- 防止手杀弱智若为
      for _, p in ipairs(players) do
        if p.role == "lord" then
          room:changeMaxHp(p,0)
        end
      end

      -- 展示3张武将牌
      for _, p in ipairs(players) do
        local general = room:getNGenerals(3)
        U.setPrivateMark(p, "&dzz_show3", general,nil)
        local ddzc = U.getPrivateMark(p, "&dzz_show3")
        local name = room:askForGeneral(p, ddzc, 0,0)
      end
      
      -- 抢地主操作
      local cjb = 0
      for i, p in ipairs(players) do
        if cjb == 0 then
          local choices = {"bj","jdz"}
          local choice = room:askForChoice(p, choices, self.name,"Skeld1v2_jdz",false,choices)
          if choice == "jdz" then --抢地主
            p.role = "lord"
            room:setPlayerMark(p,"dizhu",1)
            cjb = 999
            for _, j in ipairs(players) do
              if j ~= p then
                j.role = "rebel"
              end
              room:setPlayerProperty(j, "role_shown", true)
              room:broadcastProperty(j, "role")
            end
            local lord = room:getLord()
            room:setCurrent(lord)
          end
        end
        if i == 3 and cjb == 0 then
          for _, d in ipairs(players) do
            if d.seat == 1 then
              d.role = "lord"
              room:setPlayerMark(d,"dizhu",1)
              for _, j in ipairs(players) do
                if j ~= d then
                  j.role = "rebel"
                end
                room:setPlayerProperty(j, "role_shown", true)
                room:broadcastProperty(j, "role")
              end
              local lord = room:getLord()
              room:setCurrent(lord)
            end
          end
        end
      end


      -- 地主多发俩武将
      local generals = room:getNGenerals(#players * generalNum + 2)
      local req = Request:new(players, "AskForGeneral")
      for i, p in ipairs(players) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum - 2)
        if p.role == "lord" then
          local count = #generals
          table.insert(arg, generals[count])
          table.insert(arg, generals[count - 1])
        end
        local ddlc = U.getPrivateMark(p, "&dzz_show3")
        table.insert(arg,1,ddlc[3])
        table.insert(arg,1,ddlc[2])
        table.insert(arg,1,ddlc[1])
        req:setData(p, { arg, 1 })
        req:setDefaultReply(p, { arg[1] })
      end
      req:ask()
      local selected = {}
      for _, p in ipairs(players) do
        local general_ret
        general_ret = req:getResult(p)[1]
        room:changeHero(p, general_ret, false,false,false, true,true)
        table.insertIfNeed(selected, general_ret)
        room:changeHp(p, math.min(Fk.generals[general_ret].hp, p:getLostHp()), nil, self.name)
        if p.hp ~= Fk.generals[general_ret].hp and p.role ~= "lord" then
          room:changeHp(p,-1,nil,self.name)
        end
        room:changeShield(p, Fk.generals[general_ret].shield)
        room:setPlayerMark(p, "@[private]&dzz_show3",0)
      end
      generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
      room:returnToGeneralPile(generals)
      for _, g in ipairs(selected) do
        room:findGeneral(g)
      end
      room:askForChooseKingdom(players)
  
      for _, p in ipairs(players) do
        if p.role == "lord" then
          room:handleAddLoseSkills(p, "m_feiyang|m_bahu", nil, false)
          local a = p.player_skills
          for _, s in ipairs(a) do
            if s.lordSkill and s.visible then
              room:handleAddLoseSkills(p, "-"..s.name, nil, false)
            end
          end
        end
        room:broadcastProperty(p, "general")
      end
      for _, p in ipairs(players) do
        for _, sb in ipairs(players) do
          if sb.seat == 1 and sb.role ~= "lord" and p ~= sb then
            room:swapSeat(sb,p)
          end
        end
      end
      room:setTag("SkipNormalDeathProcess", true)
    end
  end,
}
Fk:addSkill(QDZ_1v2_rule)

local QDZ_1v2_mode = fk.CreateGameMode{
  name = "1v2QDZ_mode",
  minPlayer = 3,
  maxPlayer = 3,
  main_mode = "m_1v2_mode",
  rule = QDZ_1v2_rule,
  logic = QDZ_1v2_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 0.5 min", passed = playedTime >= 30 } }
    if Self.role ~= "lord" then
      table.insert(
        surrenderJudge,
        { text = "1v2: left you alive", passed = #table.filter(Fk:currentRoom().players, function(p) return p.rest > 0 or not p.dead end) == 2 }
      )
    end

    return surrenderJudge
  end,
  get_adjusted = function (self, player)
    if player.role == "lord" then
      return {hp = player.hp + 1, maxHp = player.maxHp + 1}
    end
    return {}
  end
}

Fk:loadTranslationTable{
  ["1v2QDZ_mode"] = "斗地主(可抢地主)",
  ["m_feiyang"] = "飞扬",
  [":m_feiyang"] = "判定阶段开始时，你可以弃置两张手牌，然后弃置自己判定区的一张牌。",
  ["#m_feiyang-invoke"] = "飞扬：你可以弃置两张手牌，弃置自己判定区的一张牌",
  ["m_bahu"] = "跋扈",
  [":m_bahu"] = "锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张【杀】。",
  ["#QDZ_1v2_rule"] = "斗地主规则",
  ["QDZ_1v2_draw2"] = "摸两张牌",
  ["QDZ_1v2_heal"] = "回复1点体力",

  ["Skeld1v2_jdz"] = "选择是否叫地主",
  
  ["dizhu"] = "地主",

  ["jdz"] = "叫地主",
  ["bj"] = "不叫",

  ["@[private]&dzz_show3"] = "已查看武将",

  ["time limitation: 0 min"] = "游戏时长达到0分钟",
  ["1v2: left you alive"] = "仅剩你和地主存活",

  [":QDZ_1v2_mode"] = desc_1v2,
}

return QDZ_1v2_mode
